<?php
namespace Modules\Mall\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Modules\Mall\Entities\Mall;
use Modules\Mall\Entities\MallPic;
use Modules\Mall\Http\Requests\MallRequest;
use Modules\Mall\Entities\Cate;
class MallController extends Controller
{
    //显示列表
    public function index()
    {
    	//获取店铺数据
        $data = Mall::paginate(10);
        return view('mall::mall.index', compact('data'));
    }

    //创建视图
    public function create(Mall $mall)
    {
		$cates=Cate::get();
		$users=User::where('status',1)->get();
		if(!$cates->toArray()){
			session()->flash('danger','还未创建分类，先创建吧');
			return redirect ('mall/cate');
		}
        return view('mall::mall.create',compact('mall','cates','users'));
    }

    //保存数据
    public function store(MallRequest $request,Mall $mall)
    {
        $mall->fill($request->except (['file','src']));
        $mall->save();
        $pics=$request->only (['src']);
        $pics=json_decode ($pics['src'],true);
        foreach($pics as $pic){
			MallPic::create([
				'mall_id'=>$mall['id'],
				'src'=>$pic['url']
			]);
		}
        return redirect('/mall/mall')->with('success', '保存成功');
    }

    //显示记录
    public function show(Mall $mall)
    {
    	$mall->status=1;
    	$mall->save();
    	session()->flash('店铺审核成功！');
        return redirect ()->back();
    }

    //编辑视图
    public function edit(Mall $mall)
    {
    	$cates=Cate::get();
    	$users=User::where('status',1)->get();
		$pics=MallPic::where('mall_id',$mall['id'])->pluck('src');
		$a=[];
		foreach($pics as $k=>$pic){
			$a[$k]['name']=1;
			$a[$k]['url']=$pic;
		}
		$pics=json_encode ($a,JSON_UNESCAPED_SLASHES);
        return view('mall::mall.edit', compact('mall','cates','pics','users'));
    }

    //更新数据
    public function update(MallRequest $request, Mall $mall)
    {
        $mall->update($request->except (['file','src']));
		$pics=$request->only (['src']);
		$pics=json_decode ($pics['src'],true);
		MallPic::where('mall_id',$mall['id'])->delete();
		foreach($pics as $pic){
			MallPic::create([
				'mall_id'=>$mall['id'],
				'src'=>$pic['url']
			]);
		}
        return redirect('/mall/mall')->with('success','更新成功');
    }

    //删除模型
    public function destroy(Mall $mall)
    {
        $mall->delete();
        MallPic::where('mall_id',$mall['id'])->delete();
        return redirect('mall/mall')->with('success','删除成功');
    }
}
